import store from '@/common/store/index'
import echarts from 'echarts'
let bgColor = "#0a0a0a";//背景
let upColor="#F25757";//涨颜色
let downColor="#6FCF77";//跌颜色

// ma  颜色
let ma5Color = "#fff";
let ma10Color = "#ffff00";
let ma20Color = "#FF8C7A";
let ma30Color = "#fff";

/**
 * 15:20 时:分 格式时间增加num分钟
 * @param {Object} time 起始时间
 * @param {Object} num
 */
function addTimeStr(time,num){ 
	let hour=time.split(':')[0];
	let mins=Number(time.split(':')[1]);
	let mins_un=parseInt((mins+num)/60);
	let hour_un=parseInt((Number(hour)+mins_un)/24);
	if(mins_un>0){
		if(hour_un>0){
			let tmpVal=((Number(hour)+mins_un)%24)+"";
			hour=tmpVal.length>1? tmpVal:'0'+tmpVal;//判断是否是一位
		}else{
			let tmpVal=Number(hour)+mins_un+"";
			hour=tmpVal.length>1? tmpVal:'0'+tmpVal;
		}
		let tmpMinsVal=((mins+num)%60)+"";
		mins=tmpMinsVal.length>1? tmpMinsVal:0+tmpMinsVal;//分钟数为 取余60的数
	}else{
		let tmpMinsVal=mins+num+"";
		mins=tmpMinsVal.length>1? tmpMinsVal:'0'+tmpMinsVal;//不大于整除60
	} 
	return hour+":"+mins;
}

//获取增加指定分钟数的 数组  如 09:30增加2分钟  结果为 ['09:31','09:32'] 
function getNextTime(startTime, endTIme, offset, resultArr) {
	let result = addTimeStr(startTime, offset);
	resultArr.push(result);
	if (result == endTIme) {
		return resultArr;
	} else {
		return getNextTime(result, endTIme, offset, resultArr);
	}
}


/**
 * 不同类型的股票的交易时间会不同  
 * @param {Object} type   hs=沪深  us=美股  hk=港股
 */
let time_arr = function(times, type) { 
	// if(type.indexOf('us')!=-1){//生成美股时间段
		let timeArr = new Array();
		timeArr.push('00:00')
		return [];
	}
	// if(type.indexOf('hs')!=-1){//生成沪深时间段
	// 	let timeArr = new Array();
	// 		timeArr.push('09:30');
	// 		timeArr.concat(getNextTime('09:30', '11:29', 1, timeArr)); 
	// 		timeArr.push('13:00');
	// 		timeArr.concat(getNextTime('13:00', '15:00', 1, timeArr)); 
	// 	return timeArr;
	// }
	// if(type.indexOf('hk')!=-1){//生成港股时间段
	// 	let timeArr = new Array();
	// 		timeArr.push('09:30');
	// 		timeArr.concat(getNextTime('09:30', '11:59', 1, timeArr)); 
	// 		timeArr.push('13:00');
  //     timeArr.concat(getNextTime('13:00', '16:00', 1, timeArr)); 
  //     console.log(timeArr)
	// 	return timeArr;
	// }
	
// }


let get_m_data = function(m_data,type) {
	let priceArr = new Array();
	let avgPrice = new Array();
	let vol = new Array();
  let times = [] // time_arr(times, type);
  m_data.forEach( item => {
    priceArr.push(item[1]);
		avgPrice.push(item[2]);
    vol.push(item[3]); 
    times.push(item[0])
  }) 
  times.push(...getNextTime(times[times.length - 1], '05:00', 1, []) ) 
  
	return {
		priceArr: priceArr,
		avgPrice: avgPrice,
		vol: vol,
		times: times
	}
}



//==========================================分时表 option

/**
 * 生成分时option 
 * @param {Object} m_data 分时数据
 * @param {Object} type 股票类型  us-美股  hs-沪深  hk-港股
 */
function initMOption(m_data,type, yestclose){
	let m_datas = get_m_data(m_data,type);
	let obj = {
		tooltip: { //弹框指示器
			trigger: 'axis',
				axisPointer: {
				type: 'cross'
			},
			formatter: function(params, ticket, callback) {
				let i = params[0].dataIndex;
	
				let color;
				if (m_datas.priceArr[i] > yestclose) {
					color ='style="color:#ff4242"';
				} else {
					color ='style="color:#26bf66"'; 
				}
	
				let html = '<div class="commColor" style="width:100px;"><div>当前价 <span  style="color:#fff" >' + m_datas.priceArr[i] + '</span></div>';
				html += '<div>均价 <span  style="color:yellow;" >' + m_datas.avgPrice[i] + '</span></div>';
				html += '<div>涨幅 <span  '+color+' >' + ratioCalculate(m_datas.priceArr[i], yestclose)+ '%</span></div>';
				html += '<div>成交量 <span  style="color:#fff" >' + m_datas.vol[i] + '</span></div></div>'
				return html;
			}
		},
		legend: { //图例控件,点击图例控制哪些系列不显示
			icon: 'rect',
			type: 'scroll',
			itemWidth: 14,
			itemHeight: 2,
			left: 0,
			top: '-1%',
			textStyle: {
				fontSize: 12,
				color: '#ccc'
			}
		},
		axisPointer: {
			show: true
		},
		color: [ma5Color, ma10Color],
		grid: [{
				id: 'gd1',
				left: '4%',
				right: '3%',
        height: '60%', //主K线的高度,
      
				top: '5%'
			},
			{
				id: 'gd2',
				left: '4%',
				right: '3%',
			
				height: '60%', //主K线的高度,
       
				top: '5%'
			}, 
			{
				id: 'gd3',
				left: '4%',
				right: '3%',
				top: '69%',
				height: '19%' //交易量图的高度
			}
		],
		xAxis: [ //==== x轴
			{ //主图 
				gridIndex: 0,
				data: m_datas.times,
				axisLabel: { //label文字设置
					show: false,
					interval:1,
					color: '#9b9da9',
				},
				splitLine: {
					show: false,
				}
			},
			{
				show:false,
				gridIndex: 1,
				data: m_datas.times,
				axisLabel: { //label文字设置
					show: false
				},
				splitLine: {
					show: false,
				}
			}, { //交易量图
				splitNumber: 2,
				type: 'category',
				gridIndex: 2,
				
				data: m_datas.times,
				axisLabel: { //label文字设置
					color: '#9b9da9',
					// interval:1,
					fontSize: 10
				},
			}
		],
		yAxis: [ //y轴
			{
				gridIndex: 0,
				scale: true, 
				splitNumber: 3,  
				axisLabel: { //label文字设置 
					inside: true, //label文字朝内对齐 
					fontWeight:'bold',
					color:function(val){ 
						if(val==yestclose){
							return '#aaa'
						}
						return val>yestclose? upColor:downColor;
					}
				},z:4,splitLine: { //分割线设置
					show: false,
					lineStyle: {
						color: '#181a23'
					}
				},  
			}, 
			{ 
				scale: true,  
				gridIndex: 1, 
				splitNumber: 3,  
				position: 'right', 
				z:4,
				axisLabel: { //label文字设置
					color:function(val){ 
						if(val==yestclose){
							return '#aaa'
						}
						return val>yestclose? upColor:downColor; 
					},
					show: true,
					type:"value",
					inside: true, //label文字朝内对齐 
					fontWeight:'bold',
					formatter:function(val,val1,val2){
						let resul=ratioCalculate(val,yestclose);
						if (isNaN(resul)) {
							return '0%'
						}
					return  Number(resul).toFixed(2)+' %'}
				},
				splitLine: { //分割线设置
					show: false,
					lineStyle: {
						color: '#181a23'
					}
				},
				axisPointer:{
					show:false,
					label:{
						formatter:function(params){ //计算右边Y轴对应的当前价的涨幅比例
							return  ratioCalculate(params.value,yestclose)+'%';
						}
					}
				}
			} 
			
			, { //交易图
				gridIndex: 2,z:4,
				splitNumber: 3,
				axisLine: {
					onZero: false
				},
				axisTick: {
					show: false
				},
				splitLine: {
					show: false
				},
				axisLabel: { //label文字设置
					color: '#c7c7c7',
					inside: true, //label文字朝内对齐 
					fontSize: 8
				},
			}
		],
		dataZoom: [
	
		],
		//animation:false,//禁止动画效果
		backgroundColor: bgColor,
		blendMode: 'source-over',
		series: [
			{
				name: '当前价',
				type: 'line',
				data: m_datas.priceArr,
				smooth: true,
				symbol: "none", //中时有小圆点
				lineStyle: {
					normal: {
						opacity: 0.8,
						color: '#ffffff',
						width: 1
					}
				}
			},
			// {
			// 	name: '均价',
			// 	type: 'line',
			// 	show: false,
			// 	data: m_datas.avgPrice,
			// 	smooth: true,
			// 	gridIndex: 0,
			// 	xAxisIndex: 0,
			// 	yAxisIndex: 0,
			// 	symbol: "none",
			// 	lineStyle: { //标线的样式
			// 		normal: {
			// 			opacity: 0.8,
			// 			color: 'yellow',
			// 			width: 0
			// 		}
			// 	}
			// },
			{  
				type: 'line', 
				data: m_datas.priceArr,
				smooth: true,
				show: false,
				symbol: "none",
				gridIndex: 1,
				xAxisIndex: 1,
				yAxisIndex: 1,
				lineStyle: { //标线的样式 
					normal: { 
						width: 1,
						color:'#fff'
					}
				}
			},
			{
				name: '交易量',
				type: 'bar',
				gridIndex: 2,
				xAxisIndex: 2,
				yAxisIndex: 2,
				data: m_datas.vol,
				barWidth: '60%',
				itemStyle: {
					normal: {
						color: function(params) {
							let colorList;
							if (m_datas.priceArr[params.dataIndex] > m_datas.priceArr[params.dataIndex-1]) {
								colorList = upColor;
							} else {
								colorList = downColor;
							}
							return colorList;
						},
					}
				}
			}
		]
	}; 
	if (store.state.xuXianData.length > 0) {
		obj.series[0].markLine = {
			symbol: 'none',
			silent: true,
			data: store.state.xuXianData.map(n => {
				let text = `下单<${n.risefall == 'rise' ? '买' : '卖'}>${n.playprice}  盈亏${n.yk}  手数${n.volume}`
				return {
					xAxis: 0,
					yAxis: n.risefall == 'rise' ? Number(n.playprice):  (Number(n.playprice) - Number(n.playprice * .0002)),
					lineStyle: {
						type: 'dashed',
						color: n.risefall == 'rise' ? 'red' : 'green'
					},
					label: {
						position: n.risefall == 'rise' ? 'insideStartTop' : 'insideStartBottom',
						formatter: text
					}
				}
			})
		}
	} else {
		delete obj.series[0].markLine
	}
	return  obj
	
}



/**
 * 计算价格涨跌幅百分比
 * @param {Object} price 当前价
 * @param {Object} yclose 昨收价
 */
function ratioCalculate(price,yclose){
  price = Number(price)
  yclose = Number(yclose)
	return ((price-yclose)/yclose*100).toFixed(3);
}









//数组处理
function splitData(rawData) {
  const d = rawData.map( item => [...item])
	let datas = []; let times = [];let vols = []; 
	for (let i = 0; i < d.length; i++) {
		datas.push(d[i]);
		times.push(d[i].splice(0, 1)[0]);
		vols.push(d[i][4]); 
  }
	return {datas:datas,times:times,vols:vols};
}


//================================MA计算公式
function calculateMA(dayCount,data) {
	let result = [];
	for (let i = 0, len = data.times.length; i < len; i++) {
		if (i < dayCount) {
			result.push('-');
			continue;
		}
		let sum = 0;
		for (let j = 0; j < dayCount; j++) {
			sum += data.datas[i - j][1];
		}
		result.push((sum / dayCount).toFixed(2));
	}
	return result;
}


//=================================================MADC计算公式

let calcEMA,calcDIF,calcDEA,calcMACD;

/*
 * 计算EMA指数平滑移动平均线，用于MACD
 * @param {number} n 时间窗口
 * @param {array} data 输入数据
 * @param {string} field 计算字段配置
 */
calcEMA=function(n,data,field){
    let i,l,ema,a;
    a=2/(n+1);
    if(field){
        //二维数组
        ema=[data[0][field]];  
        for(i=1,l=data.length;i<l;i++){
            ema.push((a*data[i][field]+(1-a)*ema[i-1]).toFixed(2));
        }
    }else{
        //普通一维数组
        ema=[data[0]];
        for(i=1,l=data.length;i<l;i++){
            ema.push((a*data[i]+(1-a)*ema[i-1]).toFixed(3) );
        }
    } 
    return ema;
};

/*
 * 计算DIF快线，用于MACD
 * @param {number} short 快速EMA时间窗口
 * @param {number} long 慢速EMA时间窗口
 * @param {array} data 输入数据
 * @param {string} field 计算字段配置
 */
calcDIF=function(short,long,data,field){
    let i,l,dif,emaShort,emaLong;
    dif=[];
    emaShort=calcEMA(short,data,field);
    emaLong=calcEMA(long,data,field);
    for(i=0,l=data.length;i<l;i++){
        dif.push((emaShort[i]-emaLong[i]).toFixed(3));
    }
    return dif;
};

/*
 * 计算DEA慢线，用于MACD
 * @param {number} mid 对dif的时间窗口
 * @param {array} dif 输入数据
 */
calcDEA=function(mid,dif){
    return calcEMA(mid,dif);
};

/*
 * 计算MACD
 * @param {number} short 快速EMA时间窗口
 * @param {number} long 慢速EMA时间窗口
 * @param {number} mid dea时间窗口
 * @param {array} data 输入数据
 * @param {string} field 计算字段配置
 */
calcMACD=function(short,long,mid,data,field){
    let i,l,dif,dea,macd,result;
    result={};
    macd=[];
    dif=calcDIF(short,long,data,field);
    dea=calcDEA(mid,dif);
    for(i=0,l=data.length;i<l;i++){
        macd.push(((dif[i]-dea[i])*2).toFixed(3));
    }
    result.dif=dif;
    result.dea=dea;
    result.macd=macd;
    return result;
};
 
 
 //=================================================MADC计算公式 end

  // 初始化数据
  // 连续性获取最后一条追加
  // 每次进入页面重新获取数据，然后连续性追加最后一条

 function initKOption(cdata){
   if (!cdata || cdata.length <= 0) {
    return false
   }
  let data = {
    vols: [],
    times: [],
    datas: []
  }
  let macd = []
  let calcMa5 = []
  let calcMa10 = []
  let calcMa20 = []
  let calcMa30 = []

   if (cdata.length > 0) {
      data = splitData(cdata);
      macd=calcMACD(12,26,9,data.datas,1); 
      calcMa5 = calculateMA(5,data)
      calcMa10 = calculateMA(10,data)
      calcMa20 = calculateMA(20,data)
      calcMa30 = calculateMA(30,data)
   }
 
	return {
			tooltip: { //弹框指示器
			trigger: 'axis',
			axisPointer: {
				type: 'cross'
      },
      alwaysShowContent: true,
			formatter: function(params, ticket, callback) {
       
        let html = ''
        if (params[0].seriesName == 'MACD') {
          html = `<div class="view">
                    <div class="margin_bottom5">${params[0].axisValue}</div>
                    <div class="view margin_left10">
                        <div class="view flex-row align-center margin_bottom5"><div class="circle margin_right5"></div>MACD：${params[0].data}</div>
                        <div class="view flex-row align-center margin_bottom5"><div class="circle margin_right5"></div>DIF：${params[1].data}</div>
                        <div class="view flex-row align-center margin_bottom5"><div class="circle margin_right5"></div>DEA：${params[2].data}</div>
                    </div>
                </div>`
        } else if (params[0].seriesName == '成交量') {
          html = `<div class="view">
                    <div class="margin_bottom5">${params[0].axisValue}</div>
                    <div class="view margin_left10">
                        <div class="view flex-row align-center margin_bottom5"><div class="circle margin_right5"></div>成交量：${params[0].data}</div>
                    </div>
                </div>`
        }
        
        else {
          html = `<div class="view">
                        <div class="margin_bottom5">${params[0].axisValue}</div>
                        <div class="view margin_left10">
                            <div class="view flex-row align-center margin_bottom5"><div class="circle margin_right5"></div>开盘：${params[0].data[1]}</div>
                            <div class="view flex-row align-center margin_bottom5"><div class="circle margin_right5"></div>结算：${params[0].data[2]}</div>
                            <div class="view flex-row align-center margin_bottom5"><div class="circle margin_right5"></div>最低：${params[0].data[3]}</div>
                            <div class="view flex-row align-center"><div class="circle margin_right5"></div>最高：${params[0].data[4]}</div>
                        </div>
                    </div>`
        }

         
				return html;
			}
			},
			legend: { //图例控件,点击图例控制哪些系列不显示
				icon: 'rect', 
				type:'scroll',
				itemWidth: 14,
				itemHeight: 2,
				left: 0,
				top: '-1%',  
				animation:true,
				textStyle: {
					fontSize: 12,
					color: '#0e99e2'
				},
				pageIconColor:'#0e99e2'
			},
			axisPointer: {
				show: true
			},
			color: [ma5Color, ma10Color, ma20Color, ma30Color],
			grid: [{
				id: 'gd1',
				left: '0%',
				right: '3%',
				height: '60%', //主K线的高度,
				top: '8%'
			}, {
				left: '0%',
				right: '3%',
				top: '66.5%',
				height: '10%' //交易量图的高度
			}, {
				left: '0%',
				right: '3%',
				top: '80%', //MACD 指标
				height: '14%'
			}],
			xAxis: [ //==== x轴
				{ //主图
					type: 'category',
					data: data.times,
					scale: true,
					boundaryGap: false,
					axisLine: {
						onZero: false
					},
					axisLabel: { //label文字设置
						show: false
					},
					splitLine: {
						show: false,
						lineStyle: {
							color: '#3a3a3e'
						}
					},
					splitNumber: 20,
					min: 'dataMin',
					max: 'dataMax'
				}, { //交易量图
					type: 'category',
					gridIndex: 1,
					data: data.times,
					axisLabel: { //label文字设置
						color: '#9b9da9',
						fontSize: 10
          },
          
				}, { //幅图
					type: 'category',
					gridIndex: 2,
					data: data.times,
					axisLabel: {
						show: false
					}
				}
			],
			yAxis: [ //y轴
				{ //==主图
					scale: true,
          z:4,
          
					axisLabel: { //label文字设置
						color: '#c7c7c7',
						inside: true, //label文字朝内对齐
					},
					splitLine: { //分割线设置
						show: false,
						lineStyle: {
							color: '#181a23'
						}
					},
				}, { //交易图
					gridIndex: 1, splitNumber: 3, z:4,
					axisLine: {
						onZero: false
					},
					axisTick: {
						show: false
					},
					splitLine: {
						show: false
					},
					axisLabel: { //label文字设置
						color: '#c7c7c7',
						inside: true, //label文字朝内对齐 
						fontSize: 8
					},
        },
         { //幅图
					z:4, gridIndex: 2,splitNumber: 4,
					axisLine: {
						onZero: false
					},
					axisTick: {
						show: false
					},
					splitLine: {
						show: false
					},
					axisLabel: { //label文字设置
						color: '#c7c7c7',
						inside: true, //label文字朝内对齐 
						fontSize: 8
					},
				}
			],
			dataZoom: [
        {
          type: 'inside',
          xAxisIndex: [0, 1,2],
          // start: 100,
          // end: 100,
          start:85,                           //数据窗口范围的起始数值
          end:100,
          top: 30,
          // zoomLock: true,
          height: 0
      }
			],
			animation: false, //禁止动画效果
			backgroundColor: bgColor,
			blendMode: 'source-over',
			series: [{
				
					type: 'candlestick',
					data: data.datas,
					barWidth: '55%',
					large: true,
					largeThreshold: 100,
					itemStyle: {
						normal: {
							color: upColor, //fd2e2e  ff4242
							color0: downColor,
							borderColor: upColor,
							borderColor0: downColor,
		
							//opacity:0.8
						}
					},
		
				}, {
					name: 'MA5',
					type: 'line',
					data: calcMa5,
					smooth: true,
					symbol: "none", //隐藏选中时有小圆点
					lineStyle: {
						normal: {
							opacity: 0.8,
							color: '#39afe6',
							width: 1
						}
					},
				},
				{
					name: 'MA10',
					type: 'line',
					data: calcMa10,
					smooth: true,
					symbol: "none",
					lineStyle: { //标线的样式
						normal: {
							opacity: 0.8,
							color: '#da6ee8',
							width: 1
						}
					}
				},
				{
					name: 'MA20',
					type: 'line',
					data: calcMa20,
					smooth: true,
					symbol: "none",
					lineStyle: {
						opacity: 0.8,
						width: 1,
						color: ma20Color
					}
				},
				{
					name: 'MA30',
					type: 'line',
					data: calcMa30,
					smooth: true,
					symbol: "none",
					lineStyle: {
						normal: {
							opacity: 0.8,
							width: 1,
							color: ma30Color
						}
					}
				}, {
					name: '成交量',
					type: 'bar',
					xAxisIndex: 1,
					yAxisIndex: 1,
					data: data.vols,
					barWidth: '60%',
					itemStyle: {
						normal: {
							color: function(params) {
								let colorList;
								if (data.datas[params.dataIndex][1] > data.datas[params.dataIndex][0]) {
									colorList = upColor;
								} else {
									colorList = downColor;
								}
								return colorList;
							},
						}
					}
				}, {
					name: 'MACD',
					type: 'bar',
					xAxisIndex: 2,
					yAxisIndex: 2,
					data: macd.macd,
					barWidth: '40%',
					itemStyle: {
						normal: {
							color: function(params) {
								let colorList;
								if (params.data >= 0) {
									colorList = upColor;
								} else {
									colorList = downColor;
								}
								return colorList;
							},
						}
					}
				}, {
					name: 'DIF',
					type: 'line',
					symbol: "none",
					xAxisIndex: 2,
					yAxisIndex: 2,
					data: macd.dif,
					lineStyle: {
						normal: {
							color: '#da6ee8',
							width: 1
						}
					}
				}, {
					name: 'DEA',
					type: 'line',
					symbol: "none",
					xAxisIndex: 2,
					yAxisIndex: 2,
					data: macd.dea,
					lineStyle: {
						normal: {
							opacity: 0.8,
							color: '#39afe6',
							width: 1
						}
					}
				}
			]
		};
		
		
}
export default {
	initMOption,
	initKOption
}